package ddz.logic.game;

import ch.qos.logback.classic.Logger;
import com.kaka.notice.Message;
import com.kaka.notice.annotation.Handler;
import ddz.constants.Crypto;
import ddz.constants.ErrCode;
import ddz.constants.ErrLevel;
import ddz.constants.OpCode;
import ddz.core.*;
import ddz.db.dao.TableDao;
import ddz.db.service.TableTokenService;
import ddz.net.LogicDataHandler;
import ddz.net.ProtocolMessage;
import ddz.protos.GameDizhu;
import org.slf4j.LoggerFactory;

/**
 * 争抢地主，包括抢或不抢
 *
 * @author zkpursuit
 */
@Handler(cmd = OpCode.cmd_qiangdizhu, type = String.class)
public class DizhuCapHandler extends LogicDataHandler {

    private static final Logger logger = (Logger) LoggerFactory.getLogger(DizhuCapHandler.class);

    @Override
    public void execute(ProtocolMessage msg) throws Exception {
        GameDizhu.CsQiangDizhu qiangDizhu = (GameDizhu.CsQiangDizhu) msg.getBody();
        TableTokenService optTokenService = this.retrieveProxy(TableTokenService.class);
        TableToken tokenInfo = optTokenService.parseToken(qiangDizhu.getToken());
        TableDao tableDao = this.retrieveProxy(TableDao.class);
        Table table = tableDao.getDesk(tokenInfo.getDeskId());
        if (table == null) {
            logger.error("玩家（" + msg.uid() + "）未加入任何房间");
            sendError(msg.ctx(), opcode(), ErrLevel.ERROR, ErrCode.no_join_room);
            return;
        }
        Player player = table.getPlayerByUid(msg.uid());
        if (player == null) {
            logger.error("玩家（" + msg.uid() + "）在" + table.getId() + "房间中无对应的数据");
            sendError(msg.ctx(), opcode(), ErrLevel.ERROR, ErrCode.data_err);
            return;
        }
        if (table.getWaitOperateSeatIndex() != player.getSeatIndex()) {
            logger.error("还未轮到玩家（" + msg.uid() + "）在" + table.getId() + "房间抢地主");
            throw new Error("还未轮到玩家抢地主11");
            //sendError(msg.ctx(), opcode(), ErrLevel.WARN, ErrCode.illegal_operation);
            //return;
        }
//        if (desk.getStep() != tokenInfo.getStep()) {
//            logger.error("还未轮到玩家（" + msg.uid() + "）在" + desk.getId() + "房间抢地主");
//            throw new Error("还未轮到玩家抢地主22");
//            //sendError(msg.ctx(), opcode(), ErrLevel.WARN, ErrCode.illegal_operation);
//            //return;
//        }

        int optype = qiangDizhu.getOpt();
        OptType optType;
        if (optype == OptType.jiaodizhu.getId()) {
            optType = OptType.jiaodizhu;
        } else if (optype == OptType.qiangdizhu.getId()) {
            optType = OptType.qiangdizhu;
        } else if (optype == OptType.bujiaodizhu.getId()) {
            optType = OptType.bujiaodizhu;
        } else {
            optType = OptType.buqiangdizhu;
        }
        table.addOptRecord(new OptRecord(optType, player.getSeatIndex()));
        int[] beis = table.getMultiple();

        if (logger.isInfoEnabled()) {
            logger.info("玩家 [{}：{}] 在 [{}] 房间中 [{}] 地主，倍率为：{}", player.getSeatIndex(), msg.uid(), table.getId(), optType, table.getMultiple());
        }

        Player[] players = table.getPlayers();
        for (Player member : players) {
            if (member != null) {
                GameDizhu.ScQiangDizhu respObj = GameDizhu.ScQiangDizhu.newBuilder()
                        .setBei(beis[member.getSeatIndex()])
                        .setOpt(optype)
                        .setOptSeat(player.getSeatIndex()).build();
                this.sendData(member.getUid(), Crypto.isCrypto, opcode(), respObj.toByteArray());
            }
        }

        int dizhuSeatIndex = table.getDizhuSeatIndex();
        if (dizhuSeatIndex == -2) {
            //全部不要地主，重新发牌
            table.setAllPassDizhuCount(table.getAllPassDizhuCount() + 1);
            if (table.getAllPassDizhuCount() >= 3) {
                table.clearRecords();
                int seatIdx = table.getBankerSeatIndex();
                table.addOptRecord(new OptRecord(OptType.jiaodizhu, seatIdx));
                seatIdx = Table.nextSeatIndex(seatIdx, table.getMaxPlayers());
                table.addOptRecord(new OptRecord(OptType.buqiangdizhu, seatIdx));
                seatIdx = Table.nextSeatIndex(seatIdx, table.getMaxPlayers());
                table.addOptRecord(new OptRecord(OptType.buqiangdizhu, seatIdx));
                //三次都不要地主则自动确定地主
                this.sendMessage(new Message(OpCode.cmd_fixed_dizhu, table));
            } else {
                table.setState(TableState.fa_pai);
                this.sendMessage(new Message(OpCode.cmd_fapai, table));
            }
        } else if (dizhuSeatIndex == -1) {
            //未结束，继续抢地主
            this.sendMessage(new Message(OpCode.cmd_show_opts, table));
        } else if (dizhuSeatIndex >= 0) {
            //已确定地主
            this.sendMessage(new Message(OpCode.cmd_fixed_dizhu, table));
        }
    }

}
